package CH9.Unit17;

/**
 * Created by Cai Ye on 2016/4/30.
 */

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.logging.Level;
import java.util.logging.Logger;

public class LoggingHandler implements InvocationHandler {
    private Object target;

    public Object bind(Object target) {
        this.target = target;
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(), this);
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = null;
        try {
            log(String.format("%s()呼叫开始……", method.getName()));
            result = method.invoke(target, args);
            log(String.format("%s()呼叫结束……", method.getName()));
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            log(e.toString());
        }
        return result;
    }

    private void log(String message) {
        Logger.getLogger(LoggingHandler.class.getName()).log(Level.INFO, message);
    }
}
